import smtplib,time,os
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header

class sendEmail:
    def __init__(self):
        #第一步：配置邮箱属性
        #发送邮箱
        self.sender='zym19880514@qq.com'
        #接收邮箱
        self.receiver='zym2569@163.com'
        #发送邮件主题
        t=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
        self.subject='自动化测试结果_'+t
        #发送邮箱服务器
        self.smtpserver='smtp.qq.com'
        #发送邮箱用户/密码
        self.username='zym19880514'
        self.password='pwrafcqzmxxighca'

    def send_mail_html(self,file):
        #第二步：准备附件，增加附件，组装邮件内容和标题
        #读取html文件内容
        with open(file,'rb') as f:
            self.mail_body=f.read()
            #组装邮件内容和标题
            self.msg=MIMEMultipart()
            #添加附件内容
            self.att=MIMEText(self.mail_body,'plain','utf-8')
            self.att["Content-Type"]='application/octet-stream'
            self.att["Content-Disposition"]='attachment;filename=report.html'
            self.msg.attach(self.att)
            #添加邮件的文本内容
            self.content='自动化测试报告详情，请查收附件'
            self.msg.attach(MIMEText(self.content,'plain','utf-8'))
            self.msg['Subject']=Header(self.subject,'utf-8')
            self.msg['From']=self.sender
            self.msg['To']=self.receiver
        #第三步：登录并发送邮件
    def send1(self,file):
        self.send_mail_html(file)
        try:
            #1--实例化smtp类
            self.smtp=smtplib.SMTP()
            #2--连接stmp服务器
            self.smtp.connect(self.smtpserver)
            #3--登录邮箱
            self.smtp.login(self.username,self.password)
            #4--设置发送人，收件人，邮件内容
            self.smtp.sendmail(self.sender,self.receiver,self.msg.as_string())
        except Exception as msg:
            print("邮件发送失败！" % msg)
        else:
            print("邮件发送成功！")
        finally:
            self.smtp.quit()

if __name__ == '__main__':
    sendEmail=sendEmail()
    sendEmail.send_mail_html(os.path.dirname(os.path.dirname(__file__))+r'/testReport/2022_03_13_15_15_40_report.html')
    sendEmail.send1(os.path.dirname(os.path.dirname(__file__))+r'/testReport/2022_03_13_15_15_40_report.html')